import cv2              #openCV
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.decomposition import PCA      #PCA降维
from sklearn.svm import SVC                #svm

data=[]     #存放图像数据
label=[]    #存放标签

#将40*10的像素为112*92像素的图像处理为400*10302的数组
for i in range(1,41):
    for j in range(1,11):
        path = "G:/postgraduate_learning/ORL/"+"s"+str(i)+"/"+str(j)+".bmp"
        #这个path啊，一定要根据自己下载到数据集的文件名和路径名设置！！！
        img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
        h, w = img.shape
        img_col = img.reshape(h*w)
        data.append(img_col)
        label.append(i)

# data变量中存储了每个图片的10304维信息,格式为列表变量（list）。变量
# label中存储了每个图片的类别标签，为数字1~40。

C_data = np.array(data)          #应用numpy生成特征向量矩阵
C_label = np.array(label)

x_train,x_test,y_train,y_test=train_test_split(C_data,C_label,test_size=0.2,random_state=256)

pca=PCA(n_components=15,svd_solver='auto').fit(x_train)      #PCA降维
x_train_pca=pca.transform(x_train)
x_test_pca=pca.transform(x_test)

svc=SVC(kernel = 'linear')
svc.fit(x_train_pca,y_train)

print('%.5f'%svc.score(x_test_pca,y_test))
